<?php
class UsersController extends Controller {
    public $viewClass = 'Smarty';
    public $uses = array('UsersModel');

    function login() {
    	$arrError = array();
		$userInfo = array();
		$email = '';
		if (!empty($this->Session->read('UserInfo'))) {
			$this->redirect('/');
		}
		if ($this->request->is('post')) {
			$email = $this->request->data('email');
			// check blank
			if (empty($this->request->data('email')) || trim($this->request->data('email')) == '') {
				$arrError[] = 'Email must be not blank';
			}
			if (empty($this->request->data('password'))  || trim($this->request->data('password')) == '') {
				$arrError[] = 'Password must be not blank';
			}		
			if (empty($arrError)) {
				// user not exist
				$userInfo = $this->UsersModel->findByEmail(trim($this->request->data('email')));
				if (empty($userInfo)) {
					$arrError[] = 'User is not exist';
				}
			}
			// wrong pass
			if (empty($arrError)) {
				if ($userInfo['UsersModel']['password'] != md5(trim($this->request->data('password')))) {
					$arrError[] = 'Wrong password';
				}
			} 
			if (empty($arrError)) {
					// everything OK, set session
				$this->Session->write('UserInfo', $userInfo);
				$this->redirect('/');
			}
		}
		$this->set('loginScreen', '1');
		$this->set('email', $email);
		$this->set('arrError', $arrError);
		$this->render('/Users/login');
    }


    function logout() {
        // destroy session
        $this->Session->delete('UserInfo');
        $this->redirect('/login');
    }
}
